import React, { Component } from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import Home from "../../pages/Home"
import CommodityClassification from "../../pages/CommodityClassification"
import CommodityManagement from "../../pages/CommodityManagement"
import UserManagement from "../../pages/UserManagement"
import RoleManagement from "../../pages/RoleManagement"
import ColumnChart from "../../pages/ColumnChart"
import LineChart from "../../pages/LineChart"
import PieChart from "../../pages/PieChart"
import http from "../../api"
import Error from "../Error"

export default class Routes extends Component {
  state = { power: [] }
  async componentDidMount() {
    const username = localStorage.getItem('grain_name')
    // 获取用户权限
    try {
      const { data } = await http.get('/rest/login/user', { params: { username } })
      const { power } = data.roleId
      this.setState({ power })
    } catch(err) {
      console.log(err.message)
    }
  }
  getPower = (str) => {
    const { power } = this.state
    return power.find(item => {
      return item === str
    })
  }
  render() {
    const { getPower } = this
    return (
      <Switch>
        <Route path="/admin/home" component={getPower('home') ? Home : Error}></Route>
        <Route path="/admin/classification" component={getPower('classification') ? CommodityClassification : Error}></Route>
        <Route path="/admin/administration" component={getPower('administration') ? CommodityManagement : Error}></Route>
        <Route path="/admin/user" component={getPower('user') ? UserManagement : Error}></Route>
        <Route path="/admin/role" component={getPower('role') ? RoleManagement : Error}></Route>
        <Route path="/admin/column" component={getPower('column') ? ColumnChart : Error}></Route>
        <Route path="/admin/line" component={getPower('line') ? LineChart : Error}></Route>
        <Route path="/admin/pie" component={getPower('pie') ? PieChart : Error}></Route>
        <Redirect to="/admin/home" component={getPower('home') ? Home : Error}></Redirect>
      </Switch>
    )
  }
}
